package com.huawei.drive.adapter;

import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.bumptech.glide.Glide;
import com.huawei.cloud.base.media.MediaHttpDownloader;
import com.huawei.cloud.base.media.MediaHttpDownloaderProgressListener;
import com.huawei.cloud.services.drive.Drive;
import com.huawei.cloud.services.drive.model.File;
import com.huawei.drive.MyApplication;
import com.huawei.drive.R;
import com.huawei.drive.hms.CredentialManager;
import com.huawei.drive.hms.HmsProxyImpl;
import com.huawei.drive.utlis.FontsUtils;
import com.huawei.drive.utlis.MyFileUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class QueryResultAdapter extends RecyclerView.Adapter<QueryResultAdapter.TikTokListViewHolder> {

    public List<File> data;
    private static final int TYPE_COMMON_ITEM = 1;
    private static final int TYPE_AD_ITEM = 2;
    private int mId;
    private int mCateory;
    private int mILike;
    private int mType;
    private int mRank;
    private Context context;

    public QueryResultAdapter(List<File> data) {
        this.data = data;
    }

    @NonNull
    @Override
    public TikTokListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        context = parent.getContext();
        View view = null;

        TikTokListViewHolder viewHolder;
        if (view == null) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false);
            viewHolder = new TikTokListViewHolder(view);
        } else {
            viewHolder = (TikTokListViewHolder) view.getTag();
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull TikTokListViewHolder holder, int position) {
        File file = data.get(position);
        String fileName = file.getFileName();

        holder.mTitle.setText(fileName);
        String id = file.getId();
        Long size = file.getSize();
        String fileSuffix = file.getFileSuffix();
//        MIME_TYPE_MAP.put(".doc", "application/msword");
//        MIME_TYPE_MAP.put(".jpg", "image/jpeg");
//        MIME_TYPE_MAP.put(".mp3", "audio/x-mpeg");
//        MIME_TYPE_MAP.put(".mp4", "video/mp4");
//        MIME_TYPE_MAP.put(".pdf", "application/pdf");
//        MIME_TYPE_MAP.put(".png", "image/png");
//        MIME_TYPE_MAP.put(".txt", "text/plain");

        String filePath = "/storage/emulated/0/Huawei/Drive/DownLoad/Demo_" + fileName;
        java.io.File file1 = new java.io.File(filePath);
        String parent_path = file1.getParent();
        java.io.File file2 = new java.io.File(parent_path);
        if (!file2.exists()) {
            file2.mkdirs();
        }

        initDownView(file, file1, holder);
        holder.mTvDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadFiles(file, filePath, file1, holder);
            }
        });


        holder.mPosition = position;
    }

    /**
     * @param bytes 转换得字节
     * @param si    是否需要单位
     * @return
     */
    public static String byteFormat(long bytes, boolean si) {
        String[] units = new String[]{" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"};
        int unit = 1024;
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        double pre = 0;
        if (bytes > 1024) {
            pre = bytes / Math.pow(unit, exp);
        } else {
            pre = (double) bytes / (double) unit;
        }
        if (si) {
            return String.format(Locale.ENGLISH, "%.1f%s", pre, units[(int) exp]);
        }
        return String.format(Locale.ENGLISH, "%.1f", pre);
    }

/*
 .setFields("category,nextCursor,files/id,files/fileName,files/size,files/fileSuffix,files/mimeType")
 */
    private void initDownView(File file, java.io.File file1, @NonNull TikTokListViewHolder holder) {
        String mimeType = file.getMimeType();
        String fileSize = byteFormat(file.getSize(),true);
        String fileSuffix = file.getFileSuffix();

        if (mimeType.contains("image")) {

            if (file1.exists()) {
                holder.mThumb.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(context)
                        .load(file1)
                        .placeholder(android.R.color.white)
                        .into(holder.mThumb);
            }else {
                holder.mThumb.setScaleType(ImageView.ScaleType.CENTER);
                holder.mThumb.setImageResource(R.mipmap.image);
            }
        } else if (mimeType.contains("video")) {
            if (file1.exists()) {
                holder.mThumb.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(context)
                        .load(file1)
                        .placeholder(android.R.color.white)
                        .into(holder.mThumb);
            }else {
                holder.mThumb.setScaleType(ImageView.ScaleType.CENTER);
                holder.mThumb.setImageResource(R.mipmap.video);
            }

        } else if (mimeType.contains("audio")) {
            holder.mThumb.setScaleType(ImageView.ScaleType.CENTER);
            holder.mThumb.setImageResource(R.mipmap.music);
        } else if (mimeType.contains("text/plain")) {
            holder.mThumb.setScaleType(ImageView.ScaleType.CENTER);
            holder.mThumb.setImageResource(R.mipmap.text);
        } else {
            holder.mThumb.setScaleType(ImageView.ScaleType.CENTER);
            holder.mThumb.setImageResource(R.mipmap.open_file);
        }
        holder.mThumb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyFileUtils.openAndroidFile(file1.getPath(), context);
            }
        });

        if (file1.exists()) {
//            holder.mTvDown.setText(R.string.delete);
            holder.mTvDown.setVisibility(View.GONE);

        } else {
            holder.mThumb.setOnClickListener(null);
            holder.mTvDown.setVisibility(View.VISIBLE);

        }

    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }


    private static final String TAG = "QueryResultAdapter";


    public class TikTokListViewHolder extends RecyclerView.ViewHolder {

        public ImageView mThumb;
        public TextView mTitle;
        public TextView mTvDown;

        public int mPosition;

        public TikTokListViewHolder(@NonNull View itemView) {
            super(itemView);
            mThumb = itemView.findViewById(R.id.itl_iv);
            mTitle = itemView.findViewById(R.id.tv_title);
            mTvDown = itemView.findViewById(R.id.tv_down);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

        }
    }

    private Drive buildDrive() {
        Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), MyApplication.getContnet()).build();
        return service;
    }

    /**
     * https://developer.huawei.com/consumer/cn/doc/development/HMS-References/drivekit-drive-files-get
     * @param file
     * @param filePath
     * @param file1
     * @param holder
     */
    private void downloadFiles(File file, String filePath, java.io.File file1, TikTokListViewHolder holder) {
        String accessToken = HmsProxyImpl.getInstance().getAccessToken();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (accessToken == null) {
                        Log.e(TAG, "run: " + "please click 'Login'.");
                        return;
                    }
                    if (file == null) {
                        Log.e(TAG, "run: " + "please click 'Login'.");
                        return;
                    }
                    Drive drive = buildDrive();
                    Drive.Files.Get request = drive.files().get(file.getId());
                    FileOutputStream fileOutputStream = new FileOutputStream(new java.io.File(filePath));
                    request.executeContentAndDownloadTo(fileOutputStream);
                    holder.mTvDown.post(new Runnable() {
                        @Override
                        public void run() {
                            initDownView(file, file1, holder);
                        }
                    });
                    Log.e(TAG, "download to " + filePath);
                } catch (Exception ex) {
                    Log.d(TAG, "download", ex);
                    Log.e(TAG, "download error " + ex.toString());
                }
            }
        }).start();
    }

}
